<?php
/**
 * (logic) 运营总表
 */
namespace App\Logic\Operation;

use App\Models\Operation\BATotal;
use App\Models\Operation\Business;
use Illuminate\Support\Facades\DB;
class CheckBusinessOperation
{

    public static function handle($date)
    {
        //运营总表
        BATotal::query()
            //->where('report_date','>=','2023-10-01')
            ->where('report_date',$date)
            ->orderBy('id')
            ->chunk(500, function ($items){
                DB::beginTransaction();
                try{
                    foreach ($items as $item){
                        echo '==========start:'.$item->report_date.'-'.$item->country_id.'-'.$item->classify_id.'========'.PHP_EOL;
                        $sessions = self::_getSessions($item->report_date,$item->country_id,$item->classify_id);
                        $item->sessions_app = $sessions[0];
                        $item->sessions_browser = $sessions[1];
                        $item->sessions_total = $sessions[2];
                        $item->page_views_app = $sessions[3];
                        $item->page_views_browser = $sessions[4];
                        $item->page_views_total = $sessions[5];
                        $item->save();
                        echo '==========end:'.$item->report_date.'-'.$item->country_id.'-'.$item->classify_id.'========'.PHP_EOL;
                    }
                    DB::commit();
                }catch (\Exception $e){
                    DB::rollBack();
                    report($e);
                }
        });
    }

    /**
     * 商业广告
     * @param $date
     * @param $countryId
     * @param $classifyId
     * @return array
     */
    private static function _getSessions($date,$countryId,$classifyId): array
    {
        $b = Business::query()
            ->where('report_date',$date)
            ->where('country_id',$countryId)
            ->where('classify_id',$classifyId)
            ->select('sessions_app','sessions_browser','sessions_total','page_views_app','page_views_browser','page_views_total','child_asin')
            ->get();
        $sessionsApp = 0;
        $sessionsBrowser = 0;
        $sessionsTotal = 0;
        $pageViewsApp = 0;
        $pageViewsBrowser = 0;
        $pageViewsTotal = 0;
        $asin = [];
        foreach ($b as $v){
            if(!in_array($v->child_asin,$asin)){
                $asin[] = $v->child_asin;
                $sessionsApp += $v->sessions_app;
                $sessionsBrowser += $v->sessions_browser;
                $sessionsTotal += $v->sessions_total;
                $pageViewsApp += $v->page_views_app;
                $pageViewsBrowser += $v->page_views_browser;
                $pageViewsTotal += $v->page_views_total;
            }
        }
        return [$sessionsApp,$sessionsBrowser,$sessionsTotal,$pageViewsApp,$pageViewsBrowser,$pageViewsTotal];
    }
}
